import { defineStore } from 'pinia'
import { ref, computed } from 'vue'

// 定义用户角色类型
type UserRole = 'admin' | 'visitor' | null

// 定义管理员凭据接口
interface AdminCredentials {
  username: string
  password: string
}

// 定义用户状态接口
interface UserState {
  isLoggedIn: boolean
  role: UserRole
  username: string
  loginTime: number | null
}

export const useUserStore = defineStore('DaMingHuUser', () => {
  // 状态
  const isLoggedIn = ref(false)
  const userRole = ref<UserRole>(null)
  const username = ref('')
  const loginTime = ref<number | null>(null)
  const lastActivity = ref<number>(Date.now())

  // 硬编码的管理员账号密码
  const ADMIN_CREDENTIALS: AdminCredentials = {
    username: 'admin',
    password: 'admin123'
  }

  // 计算属性
  const userInfo = computed(() => ({
    username: username.value,
    role: userRole.value,
    isLoggedIn: isLoggedIn.value,
    loginTime: loginTime.value
  }))

  // 登录方法 - 管理员
  function loginAsAdmin(inputUsername: string, inputPassword: string): boolean {
    if (inputUsername === ADMIN_CREDENTIALS.username && inputPassword === ADMIN_CREDENTIALS.password) {
      isLoggedIn.value = true
      userRole.value = 'admin'
      username.value = inputUsername
      loginTime.value = Date.now()
      lastActivity.value = Date.now()
      return true
    }
    return false
  }

  // 登录方法 - 游客
  function loginAsVisitor(visitorName: string = '游客'): boolean {
    isLoggedIn.value = true
    userRole.value = 'visitor'
    username.value = visitorName || '游客'
    loginTime.value = Date.now()
    lastActivity.value = Date.now()
    return true
  }

  // 登出方法
  function logout(): void {
    isLoggedIn.value = false
    userRole.value = null
    username.value = ''
    loginTime.value = null
  }

  // 更新最后活动时间
  function updateActivity(): void {
    lastActivity.value = Date.now()
  }

  // 检查是否已登录
  function checkAuth(): boolean {
    return isLoggedIn.value
  }

  // 检查是否是管理员
  function isAdmin(): boolean {
    return userRole.value === 'admin' && isLoggedIn.value
  }

  // 检查是否是游客
  function isVisitor(): boolean {
    return userRole.value === 'visitor' && isLoggedIn.value
  }

  return {
    // 状态
    isLoggedIn,
    userRole,
    username,
    loginTime,

    // 计算属性
    userInfo,

    // 方法
    loginAsAdmin,
    loginAsVisitor,
    logout,
    updateActivity,
    checkAuth,
    isAdmin,
    isVisitor
  }
}, {
  persist: true // 启用状态持久化
})
